package org.example2;

import java.util.concurrent.TimeUnit;

/*
     主要比较线程sleep在synchronized代码块"内和外",线程状态的差异.
     结果是一致的.都是TIMED_WAITING (sleeping)
 */
public class ThreadStateTest2 {
    public static void main(String[] args) {

        Object lock = new Object();
/* 进入 synchronized 直接sleep,查看状态
"线程1" #23 prio=5 os_prio=0 tid=0x000000003764b000 nid=0x9248 waiting on condition [0x0000000037fee000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at java.lang.Thread.sleep(Thread.java:340)
        at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
        at org.example2.ThreadStateTest2$1.run(ThreadStateTest2.java:15)
        - locked <0x00000006c1a6a4a8> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
        - None
-------------------------------------------------------------------------------------------------------------------------
执行完锁.wait方法后
"线程1" #23 prio=5 os_prio=0 tid=0x000000003764b000 nid=0x9248 in Object.wait() [0x0000000037fee000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x00000006c1a6a4a8> (a java.lang.Object)
        at java.lang.Object.wait(Object.java:502)
        at org.example2.ThreadStateTest2$1.run(ThreadStateTest2.java:17)
        - locked <0x00000006c1a6a4a8> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
        - None

 */
        new Thread(new Runnable() {
            public void run() {
                synchronized (lock) {
                    try {
                        System.out.println("线程1马上休息了");
                        TimeUnit.MINUTES.sleep(2);
                        System.out.println("线程1马上wait了");
                        lock.wait();
                        TimeUnit.MINUTES.sleep(2);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }, "线程1").start();

/*
  "线程2" #24 prio=5 os_prio=0 tid=0x0000000037673000 nid=0xbbb8 waiting on condition [0x000000003844f000]
     java.lang.Thread.State: TIMED_WAITING (sleeping)
          at java.lang.Thread.sleep(Native Method)
          at java.lang.Thread.sleep(Thread.java:340)
          at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
          at org.example2.ThreadStateTest2$2.run(ThreadStateTest2.java:30)
          at java.lang.Thread.run(Thread.java:745)

     Locked ownable synchronizers:
          - None
 */
        new Thread(new Runnable() {
            public void run() {
                try {
                    TimeUnit.MINUTES.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "线程2").start();


    }
}
